<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能知识库系统</title>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --background-color: #f5f6fa;
            --card-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        }

        body {
            background-color: var(--background-color);
            min-height: 100vh;
        }

        .container {
            display: flex;
            height: 100vh;
            padding: 20px;
            gap: 20px;
        }

        /* 左侧边栏 */
        .sidebar {
            width: 30%;
            min-width: 300px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        /* 文件管理模块 */
        .file-management {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--card-shadow);
        }

        .upload-section {
            margin-bottom: 20px;
        }

        #fileInput {
            display: none;
        }

        .custom-upload-btn {
            background-color: var(--secondary-color);
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            transition: opacity 0.2s;
            display: inline-block;
        }

        .custom-upload-btn:hover {
            opacity: 0.9;
        }

        .file-list {
            margin-top: 15px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .file-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* 右侧主内容区 */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        /* 问答交互区 */
        .chat-section {
            flex: 1;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--card-shadow);
            display: flex;
            flex-direction: column;
        }

        .chat-history {
            flex: 1;
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 4px;
        }

        .input-group {
            display: flex;
            gap: 10px;
        }

        #questionInput {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .ask-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .ask-btn:hover {
            background-color: var(--secondary-color);
        }

        /* 历史记录区 */
        .history-section {
            height: 300px;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--card-shadow);
        }

        .history-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .history-item:hover {
            background-color: #f8f9fa;
        }

        /* 添加加载动画 */
        .loading-spinner {
            animation: spin 1s linear infinite;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧边栏 -->
        <div class="sidebar">
            <div class="file-management">
                <h2>📁 文件管理</h2>
                <div class="upload-section">
                    <label class="custom-upload-btn">
                        📤 上传文件
                        <input type="file" id="fileInput">
                    </label>
                    <button onclick="uploadFile()" class="ask-btn" style="margin-top:10px">确认上传</button>
                </div>
                <div class="file-list">
                    <h3>已上传文件</h3>
                    <div id="fileListItems">
                        {% for file in files %}
                            <div class="file-item">
                                <span>{{ file }}</span>
                                <button class="delete-btn">🗑️</button>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧主内容 -->
        <div class="main-content">
            <!-- 问答交互区 -->
            <div class="chat-section">
                <h2>💬 智能问答</h2>
                <div class="chat-history" id="chatHistory"></div>
                <div class="input-group">
                    <input type="text" id="questionInput" placeholder="输入您的问题...">
                    <button onclick="askQuestion()" class="ask-btn">发送</button>
                </div>
            </div>

            <!-- 历史记录区 -->
            <div class="history-section">
                <h2>📜 问答历史</h2>
                <div id="historyList"></div>
            </div>
        </div>
    </div>

    <script>
        let chatHistory = [];

        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            if (!fileInput.files[0]) {
                alert('请先选择文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('/upload/', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const data = await response.json();
                    addFileItem(data.filename);
                    fileInput.value = '';
                    alert('上传成功');
                }
            } catch (error) {
                alert('上传失败: ' + error.message);
            }
        }

        function addFileItem(filename) {
            const fileList = document.getElementById('fileListItems');
            const item = document.createElement('div');
            item.className = 'file-item';
            item.innerHTML = `
                <span>${filename}</span>
                <button class="delete-btn">🗑️</button>
            `;
            fileList.appendChild(item);
        }

        async function askQuestion() {
            const input = document.getElementById('questionInput');
            const question = input.value.trim();
            if (!question) return;

            // 添加到聊天历史
            addChatMessage(question, 'user');

            try {
                const response = await fetch('/ask/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `question=${encodeURIComponent(question)}`
                });

                if (response.ok) {
                    const data = await response.json();
                    addChatMessage(data.answer, 'bot');
                    saveHistory(question, data.answer);
                }
            } catch (error) {
                addChatMessage('请求失败，请稍后再试', 'error');
            }

            input.value = '';
        }

        function addChatMessage(content, type) {
            const chatHistory = document.getElementById('chatHistory');
            const message = document.createElement('div');
            message.className = `message ${type}-message`;
            message.innerHTML = `
                <div class="message-content">${content}</div>
            `;
            chatHistory.appendChild(message);
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        function saveHistory(question, answer) {
            chatHistory.push({
                question,
                answer,
                timestamp: new Date().toLocaleString()
            });
            updateHistoryList();
        }

        function updateHistoryList() {
            const historyList = document.getElementById('historyList');
            historyList.innerHTML = chatHistory
                .map((item, index) => `
                    <div class="history-item" onclick="loadHistory(${index})">
                        <div>${item.question}</div>
                        <small>${item.timestamp}</small>
                    </div>
                `)
                .join('');
        }

        function loadHistory(index) {
            const item = chatHistory[index];
            const chatHistoryDiv = document.getElementById('chatHistory');
            chatHistoryDiv.innerHTML = `
                <div class="message user-message">
                    <div class="message-content">${item.question}</div>
                </div>
                <div class="message bot-message">
                    <div class="message-content">${item.answer}</div>
                </div>
            `;
        }
    </script>
</body>
</html>